<style scoped>
@import '../styles/Login.css';
</style>

<template>
  <div class="login-container">
    <h2 class="form-title">登录</h2>
    <form ref="formRef">
      <div class="input-group">
        <label for="username">用户名</label>
        <br>
        <input
            type="text"
            name="username"
            v-model="form.username"
            required
            placeholder="请输入用户名"
        />
      </div>
      <div class="input-group">
        <label for="password">密码</label>
        <br>
        <input
            type="password"
            name="password"
            v-model="form.password"
            required
            placeholder="请输入密码"
        />
      </div>
      <div class="forgot-password">
        <a href="#">忘记密码？</a>
      </div>
      <button class="btn" type="button" @click="handleSubmit">登录</button>
    </form>

    <div class="register-link">
      <p>还未注册？</p>
      <a @click="handleRegisterLink">加入我们，一起加油！</a>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue';
import axios from "@/api/server";
import { jwtDecode } from "jwt-decode";
import router from "@/router";
import { useUserStore } from '@/store/useUserstore';

export default {
  name: 'Login',
  data() {
    return {
      form: {
        username: '',
        password: ''
      }
    };
  },
  methods: {
    handleSubmit() {
      // 手动表单校验
      if (!this.form.username) {
        this.$message.error("请输入用户名");
        return;
      }
      if (!this.form.password) {
        this.$message.error("请输入密码");
        return;
      }

      // 发送登录请求
      this.login();
    },
    async login() {
      try {
        const response = await axios.post("/users/login", {
          username: this.form.username,
          password: this.form.password,
        });

        if (response.data.code === 1) {
          this.$message.success("登录成功");
          const token = response.data.data.token;
          const userStore = useUserStore();

          const decodedToken = jwtDecode(token);
          console.log(decodedToken);

          userStore.setToken(token);
          localStorage.setItem("token", token);
          console.log(userStore.token);

          userStore.setUserInfo(decodedToken);
          localStorage.setItem("userInfo", JSON.stringify(decodedToken));
          console.log(userStore.userInfo);

          router.push("/home").then(() => {
            window.location.reload();
          });

        } else {
          this.$message.error("账号或密码错误");
        }
      } catch (error) {
        console.error("登录失败", error);
        this.$message.error("登录请求失败");
      }
    },
    handleRegisterLink() {
      router.push('/register');
    }
  },
  setup() {
    const userStore = useUserStore();

    onMounted(() => {
      document.body.classList.add('login_body');
      console.log('✅ [测试] userStore.token:', userStore.token);
      console.log('✅ [测试] userStore.userInfo:', userStore.userInfo.name);

      // 也可以输出 localStorage 里的值对比验证
      console.log('✅ [测试] localStorage.token:', localStorage.getItem('token'));
      console.log('✅ [测试] localStorage.userInfo:', JSON.parse(localStorage.getItem('userInfo')));
    });

    onUnmounted(() => {
      document.body.classList.remove('login_body');
    });
  }
};
</script>
